//
//  DetailViewController.swift
//  CompareBuying
//
//  Created by 唐先才 on 16/2/16.
//  Copyright © 2016年 唐先才. All rights reserved.
//

import UIKit

class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate {

    var tableView: UITableView?
    var dataArray: NSMutableArray = []
    var commentDataArray: NSMutableArray = []
    var likeDataArray: NSMutableArray = []
    var parameters: NSDictionary?
    var pic_url: String?
    var headView: UIView?
    var headImage: UIImageView?
//    var refreshCount = 0
    var webHeight: CGFloat?
    var web: UIWebView?
    var modelWeb: TxcModel?
    var goodsID: String?
    
    override func viewWillAppear(animated: Bool) {
        self.tabBarController?.tabBar.hidden = true
        self.title = "商品详情"
    }
    
    override func viewWillDisappear(animated: Bool) {
        self.tabBarController?.tabBar.hidden = false
//        self.navigationController?.navigationBarHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()
        self.createToolBar()
        self.createData()
        self.createUI()
    }

    func createToolBar() {
    
        let toolBar = UIToolbar(frame: CGRect(x: 0, y: HEIGHT - 44 - 64, width: WIDTH, height: 44))
        toolBar.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(toolBar)
        
        let imgArray = ["praise_gray", "collect_gray", "cart_gray"]
        let sImgArray = ["praise_red", "collect_red", "cart_red"]
        for index in 0..<3 {
            let button = UIButton(type: .Custom)
            button.frame = CGRect(x: CGFloat(index) * WIDTH / 4.0, y: 0, width: WIDTH / 4.0, height: 20)
            button.setImage(UIImage(named: imgArray[index]), forState: .Normal)
            button.setImage(UIImage(named: sImgArray[index]), forState: .Selected)
            button.tag = 1000 + index
            button.addTarget(self, action: "clickAction:", forControlEvents: .TouchUpInside)
            let label = UILabel(frame: CGRect(x: CGFloat(index) * WIDTH / 4.0, y: 20, width: WIDTH / 4.0, height: 20))
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(11)
            if index == 0 {
                label.text = "赞"
            } else if index == 1 {
                label.text = "收藏"
            } else {
                label.text = "购物车"
            }
            toolBar.addSubview(button)
            toolBar.addSubview(label)
        }
        let goBtn = UIButton(type: .Custom)
        goBtn.frame = CGRect(x: CGFloat(3) * WIDTH / 4, y: 0, width: WIDTH / 4, height: 44)
        goBtn.backgroundColor = UIColor.orangeColor()
        goBtn.setTitle("立即购买", forState: .Normal)
        goBtn.addTarget(self, action: "goBuy", forControlEvents: .TouchUpInside)
        toolBar.addSubview(goBtn)
    }
    
    func clickAction(button: UIButton) {
    
    }
    
    func goBuy(button: UIButton) {
    
    }
    
    func createData() {
        let manager = AFHTTPRequestOperationManager()
        //第一部分
        manager.POST(scroller_detail, parameters: self.parameters, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
            guard let array = responseObject as? [[String: AnyObject]] else {
                return
            }
            for dict in array {
                let model = TxcModel.modelWithDict(dict)
                self.dataArray.addObject(model)
                
            }
            self.createWeb()
            guard let tableView = self.tableView else {
                return
            }
            tableView.reloadData()
            }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
                
        }
        //第三部分
        guard let str = self.goodsID else {
            return
        }
        let parameters3 = ["clientLanType": "1",
                           "infoID": str,
                           "pageIndex": "1",
                           "pageSize": "2"
                          ]
        manager.POST(collectComment_url, parameters: parameters3, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
            guard let array = responseObject as? [[String: AnyObject]] else {
                print("评论解包失败")
                return
            }
            for dict3 in array {
                let model = TxcModel.modelWithDict(dict3)
                self.commentDataArray.addObject(model)
            }
            guard let tableView = self.tableView else {
                return
            }
            tableView.reloadData()
            }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
                print("_____\(error)")
        }
        
        //第四部分
        let parameters4 = ["catUrl": "",
                           "homeShow": "1",
                           "infoID": str,
                           "infoType": "5",
                           "keyWord": "",
                           "mayLikeCatCount": "4"
                           ]
        manager.POST(collectLike_url, parameters: parameters4, success: { (operation: AFHTTPRequestOperation!, responseObject:AnyObject!) -> Void in
            guard let array = responseObject as? [[String: AnyObject]] else {
                print("猜你喜欢解包失败")
                return
            }
            for dict4 in array {
                let model = TxcModel.modelWithDict(dict4)
                self.likeDataArray.addObject(model)
            }
            guard let tableView = self.tableView else {
                return
            }
            tableView.reloadData()
            }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
        }
    }
    
    func createUI() {
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: WIDTH, height: HEIGHT - 44 - 64), style: .Grouped)
        guard let tableView = tableView else {
            print("详情页tableView创建失败")
            return
        }
//        tableView.backgroundColor = UIColor.whiteColor()
//        tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
        tableView.dataSource = self
        tableView.delegate = self
        self.view.addSubview(tableView)
        headView = UIView()
        headImage = UIImageView()
        guard let headView = headView, headImage = headImage else {
            return
        }
        
        headView.frame = CGRect(x: 0, y: 0, width: WIDTH, height: 350)
        headView.backgroundColor = UIColor.whiteColor()
        headImage.frame = headView.frame
        headImage.contentMode = UIViewContentMode.ScaleAspectFit
        headImage.sd_setImageWithURL(NSURL(string: self.pic_url!))
        headView.addSubview(headImage)
        tableView.tableHeaderView = headView
        let nib1 = UINib(nibName: "DetailCellOne", bundle: NSBundle.mainBundle())
        tableView.registerNib(nib1, forCellReuseIdentifier: "detailCellOne")
        let nib3 = UINib(nibName: "DetailCellThree", bundle: NSBundle.mainBundle())
        tableView.registerNib(nib3, forCellReuseIdentifier: "detailCellThree")
        let nib4 = UINib(nibName: "DetailCellFour", bundle: NSBundle.mainBundle())
        tableView.registerNib(nib4, forCellReuseIdentifier: "detailCellFour")
    }

    func createWeb() {
        web = UIWebView()
        guard let web = web else {
            return
        }
        guard let modelWeb = self.dataArray[0] as? TxcModel else {
            print("model传值失败")
            return
        }
        web.frame = CGRect(x: 0, y: 0, width: WIDTH, height: 100)
        web.delegate = self
        web.scrollView.userInteractionEnabled = true
        web.scrollView.scrollEnabled = false
        guard let content = modelWeb.InfoContent else {
            return
        }
//        let string = "<head><style>img{max-width:320px !important;}</style></head>" + content
        let string = "<head><style>img{max-width:300px !important;}</style></head>" + content
        web.loadHTMLString(string, baseURL: nil)
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        } else if section == 1 {
            return 1
        } else if section == 2 {
            if self.commentDataArray.count > 0 {
                return self.commentDataArray.count + 1
            }
        }
        return self.likeDataArray.count + 1
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let detailCellOne = DetailCellOne.detailCellOneWith(tableView, dataArray: self.dataArray, indexPath: indexPath)
            return detailCellOne
        } else if indexPath.section == 1 {
            var cell1 = tableView.dequeueReusableCellWithIdentifier("cell1")
            if (cell1 == nil) {
                cell1 = UITableViewCell(style: .Default, reuseIdentifier: "cell1")
            }
            guard let webCell = cell1 else {
                print("cell1 解包失败")
                return UITableViewCell()
            }
            guard let web = self.web else {
                return UITableViewCell()
            }
            if self.dataArray.count > 0 {
                if let model = self.dataArray[indexPath.row] as? TxcModel {
                    modelWeb = model
                    webCell.contentView.addSubview(web)
                }
            }
            return webCell
        } else if indexPath.section == 2 {
            let detailCellThree = DetailCellThree.detailCellThreeWith(tableView, dataArray: self.commentDataArray, indexPath: indexPath)
            return detailCellThree
        } else if indexPath.section == 3 {
            let detailCellFour = DetailCellFour.detailCellFourWith(tableView, dataArray: self.likeDataArray, indexPath: indexPath)
            return detailCellFour
        }
        return UITableViewCell()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        guard let web = self.web, tableView = self.tableView else {
            print("实现web代理方法失败")
            return
        }
        let str = webView.stringByEvaluatingJavaScriptFromString("document.body.offsetHeight")
        webHeight = CGFloat((str! as NSString).floatValue)
//        print("++++\(webHeight)+++++")
        guard let webH = webHeight else {
            return
        }
        web.frame = CGRect(x: 0, y: 0, width: WIDTH, height: webH)
        tableView.reloadData()
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        guard let web = self.web else {
//            print("height创建失败")
            return 0
        }
        if indexPath.section == 0 {
            return 100
        } else if indexPath.section == 1 {
            return web.frame.size.height + 20
        } else if indexPath.section == 2 {
            if indexPath.row == 0 {
                return 30
            }
            if self.commentDataArray.count > 0 {
                guard let model = self.commentDataArray[indexPath.row - 1] as? TxcModel else {
                    return 0
                }
                if model.ReviewContent == nil {
                    return 40
                }
                return 80
            }
        } else if indexPath.section == 3 {
            if indexPath.row == 0 {
                return 30
            }
            return 100
        }
        return 0
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 1
        } else if section == 2{
            return 10
        } else if section == 3 {
            return 10
        }
        return 0
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1
    }

    func scrollViewDidScroll(scrollView: UIScrollView) {
        guard let headImage = headImage else {
            return
        }
        var offset = tableView?.contentOffset.y
        if offset > 0 {
            offset = 0
        }
        guard let offsetNew = offset else {
            return
        }
        headImage.frame = CGRect(x: 0 + offsetNew / 2, y: offsetNew, width: WIDTH - offsetNew * 0.8, height: 350 - offsetNew)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}